package ie.ul.breakthrough;

import java.util.ArrayList;
import java.util.Collections;

public class OnePlyPlayer extends Player {

	public OnePlyPlayer(String pName) {
		super(pName);
	}

	public void initialize(char pColour) {
		colour = pColour;
	}

	public static final double MAX_EVAL = 1000000.0;

	public static final double MIN_EVAL = -1000000.0;

	protected double evalFunction(Breakthrough bt) {
		int row, col;
		int size = bt.size();

		for (col = 0; col < size; col++) {
			if (bt.positionOccupant(0, col) == 'W') {
				return MIN_EVAL;
			}
		}

		for (col = 0; col < size; col++) {
			if (bt.positionOccupant(size - 1, col) == 'B') {
				return MAX_EVAL;
			}
		}

		double sum = 0.0;

		for (row = 0; row < size; row++) {
			for (col = 0; col < size; col++) {
				char piece = bt.positionOccupant(row, col);
				if (piece == 'B') {
					sum += row;
				} else if (piece == 'W') {
					sum -= row;
				}
			}
		}
		return sum;
	}

	public BreakthroughMove makeMove(Breakthrough game) {
		ArrayList<BreakthroughMove> possibleMoves;
		possibleMoves = game.generateMoves(colour);
		Collections.shuffle(possibleMoves);

		BreakthroughMove bestMove = null;
		double bestEval = 0.0;

		for (int i = 0; i < possibleMoves.size(); i++) {
			BreakthroughMove move = possibleMoves.get(i);

			Breakthrough btCopy = new Breakthrough(game);
			btCopy.makeMove(colour, move);
			double eval = evalFunction(btCopy);

			if (i == 0) {
				bestEval = eval;
				bestMove = move;

			} else {
				if (colour == 'B') {
					if (eval > bestEval) {
						bestEval = eval;
						bestMove = move;
					}

				} else {
					if (eval < bestEval) {
						bestEval = eval;
						bestMove = move;
					}
				}
			}
		}
		return bestMove;
	}
}
